<?php

namespace app\api\controller;

use app\admin\model\Price;
use app\admin\model\Goods;
use app\common\controller\Api;
use app\common\library\Acsign;
use app\common\model\Authentication;
use think\Config;
use think\Db;
use think\Log;

/**
 * 首页接口
 */
class Contract extends Api
{
    protected $noNeedLogin = ['addPersonalUser','search'];
    protected $noNeedRight = ['*'];
    public function _initialize(){
        parent::_initialize();
    }

    /**
     * 实名认证
     */
    public function authentication()
    {
        $userid = $this->auth->id;
        $data = request()->param();
        if(empty($data['type'])) $this->error('请选择认证类型');//认证类型:1=个人认证,2=企业认证
        if(empty($data['realName'])) $this->error('姓名不能为空');
        if(empty($data['idCardNo'])) $this->error('身份证号不能为空');
        if(empty($data['mobile'])) $this->error('手机号不能为空');
        if($data['type'] == 2 && empty($data['creditCode'])) $this->error('社会统一信用代码不能为空');
        $asignInstance = new Acsign();
//        if($data['type'] == 1){
            //个人运营商三要素认证
            $user = array();
        $user["authTypeList"] = array(151,152);
            $user["realName"] = $data['realName'];
            $user["idCardNo"] = $data['idCardNo'];
            $user["mobile"] = $data['mobile'];
            $user["bizId"] = time().rand(100,999);
//            $user["redirectUrl"] = request()->domain().'/api/contract/addPersonalUser?uid='.$userid;
            $user["notifyUrl"] = request()->domain().'/api/contract/addPersonalUser?uid='.$userid;
            $result = $asignInstance->authPersonIdentifyUrl($user);
//        }else{
//            $company = array();
//            $company["companyName"] = $data['realName'];
//            $company["creditCode"] = $data['creditCode'];
//            $company["idCardNo"] = $data['idCardNo'];
//            $company["mobile"] = $data['mobile'];
//            $result = $asignInstance->authPersonIdentifyUrl($company);
//        }
        if($result['rt'] == true){
            $log = Authentication::where('user_id',$userid)->find();
            if($log){
                Authentication::where('user_id',$userid)->update($data);
            }else{
                $data['user_id'] = $userid;
                $data['serialNo'] = $result['data']['serialNo'];
                Authentication::create($data);
            }
        }
        $this->success('请求成功',$result);
    }
    /**
     * 上传合同/上传待签署文件
     */
    public function index($order_id)
    {
        $order = db('order')->where('id',$order_id)->find();
        $buyer = Authentication::where('user_id',$order['user_id'])->find();
        $seller = Authentication::where('user_id',$order['seller_id'])->find();
        $goods = \db('goods')->where('id',$order['good_id'])->find();
        //1卖出 2买入
        if($order['is_seller'] == 1){
            $buyer_address = '';
            $seller_address = $goods['place_origin'];
        }else{
            $buyer_address = $goods['place_origin'];
            $seller_address = '';
        }
        $asignInstance = new Acsign();
//        $re = $asignInstance->getContract('TN115F0853CBDE4C37AF1AEC9E61CF175D');
//        print_r($re);die;
        //上传待签署文件（使用模板的）
        $contractNo = "HT".time().rand(100,999);
        $contract = array();
        $contract["contractName"] = "买卖合同";
        $contract["contractNo"] = $contractNo;
        $contract["signOrder"] = 1;
        $contract["validityTime"] = "30";
        // 爱签平台制作模板
        $templates = array();
        $template = array();
        // 填充参数  key为参数名称（dataKey），value为填充值
        $fillData = [
            'buyer_address' => $buyer_address,//买家地址
            'buyer_name' => $buyer['realName'],//买家姓名
            'buyer_phone' => $buyer['mobile'],//买家电话
            'buyer_no' => $buyer['idCardNo'],
            'cashpledge' => $order['earnest'],//押金
            'money' => $order['total_price'],//价款
            'num' => $goods['num'].'kg',//数量
            'object' => $goods['title'],//合同标的
            'seller_address' => $seller_address,//卖家地址
            'seller_name' => $seller['realName'],//卖家姓名
            'seller_phone' => $seller['mobile'],//卖家电话
            'seller_no' => $seller['idCardNo'],
        ];
        $template["fillData"] = $fillData;
        // 模板编号
//        $template["templateNo"] = 'TN9835415EEB384CF2AB36B9806342B1E4';
        $template["templateNo"] = 'TNB7CB8E5048CC4820B9153332F35B3105';
        $templates = array($template);
        $contract["templates"] = $templates;
        Db::startTrans();
        try {
            $result = $asignInstance->createContract($contract, null);
            if($result['rt'] == 1){
                $res = $this->addSigner($contractNo,'seller');
                print_r($res);die;
                //修改订单签署链接
            }
            print_r($result);die;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('请求成功');
    }

    /**
     * 添加签署方
     */
    public function addSigner($contractNo,$signKey='seller',$signKey1='buyer')
    {
        $asignInstance = new Acsign();
        $contractUserInput = array();
        $contractUserInput["account"] = rand(1,9);//户唯一识别码
        $contractUserInput["contractNo"] = $contractNo;//合同唯一编码
//        $contractUserInput["isNotice"] = 1;

        // 关键字签 签署人1
        $signStrategyKey = array();
        $signStrategyKey["attachNo"] = 1;
        $signStrategyKey["locationMode"] = 3;
        $signStrategyKey["signKey"] = $signKey;
        $signStrategyKey["signType"] = 1;
        $signStrategyList = array($signStrategyKey);
        $contractUserInput["signStrategyList"] = $signStrategyList;
        $contractUserInput["signType"] = 3;
        $contractUserInput["validateType"] = 8;

        // 签署人2
        $contractUserInput2 = array();
        $contractUserInput2["account"] = rand(1,9);
        $contractUserInput2["contractNo"] = $contractNo;
        $contractUserInput2["signType"] = 3;
        $contractUserInput2["validateType"] = 8;

        // 关键字签
        $signStrategyKey2 = array();
        $signStrategyKey2["attachNo"] = 1;
        $signStrategyKey2["locationMode"] = 3;
        $signStrategyKey2["signKey"] = $signKey1;
        $signStrategyList2 = array($signStrategyKey2);
        $contractUserInput2["signStrategyList"] = $signStrategyList2;
        $contractUserList = array($contractUserInput, $contractUserInput2);
        $result = $asignInstance->addSigner($contractUserList);
        return $result;
    }

    /**
     * 添加个人用户
     */
    public function addPersonalUser()
    {
        $datas = request()->param();
        Log::info('实名认证返回信息'.json_encode($datas));
        $userid = $datas['uid'];
        if(isset($datas['result']) && $datas['result'] == 1){
            $data = Authentication::where('user_id',$userid)->find();
            Authentication::where('id',$data['id'])->update([
                'serial_no' => $data['serialNo'],
                'is_attestation' => 2
            ]);
            $asignInstance = new Acsign();
            $user = array();
            $user["account"] = $data['serialNo'];//用户唯一识别码
//            $user["serialNo"] = time();
            $user["name"] = $data['realName'];
            $user["idCard"] = $data['idCardNo'];
            $user["mobile"] = $data['mobile'];
            $user["isNotice"] = 1;
            $result = $asignInstance->addPersonalUserV2($user);
        }
    }

    /**
     * 查询实名认证详细信息
     */
    public function search()
    {
        $asignInstance = new Acsign();
        $userid = request()->param('uid');
        $data = Authentication::where('user_id',$userid)->find();
        $result = $asignInstance->getAuthRecordInfo($data['serialNo']);
        print_r($result);die;
    }
}
